<template>
	<view class="material-wrapper">
		<view class="fixed-area">
			<scroll-view class="top-tabs-view" scroll-x="true" :scroll-left="scrollLeft">
				<block v-for="(item,index) in tabList" :key="index">
					<view class="tabs-item-wrap" @click="swichMenu(item.value)">
						<view class="tabs-item">
							<view class="tabs-item-txt" :class="[currentTab==item.value ? 'theme-color' : '']">
								{{item.name}}
							</view>
							<view class="tabs-item-bottom" :class="[currentTab==item.value ? 'theme-color' : '']">
							</view>
						</view>
					</view>
				</block>
			</scroll-view>
			<!-- #ifdef MP-WEIXIN -->
			<view class="material-type" style="justify-content: space-around;">
				<block v-for="(item,index) in wxTypeList" :key="index">
					<view class="type-item" :class="[currentType==item.value?'select-type':'']"
						@tap="tapMaterialType(item)">
						{{item.label}}
					</view>
				</block>
			</view>
			<!-- #endif -->
			<!-- #ifndef MP-WEIXIN -->
			<view class="material-type">
				<block v-for="(item,index) in nonWxTypeList" :key="index">
					<view class="type-item" :class="[currentType==item.value?'select-type':'']"
						@tap="tapMaterialType(item)">
						{{item.label}}
					</view>
				</block>
			</view>
			<!-- #endif -->
		</view>
		<mescroll-uni ref="mescrollRef" :fixed="true" :top="178" :up="upOption" @up="getMaterialAll"
			@down="downCallback" @init="mescrollInit">
			<view class="material-con">
				<view v-for="(item,index) in materialList" :key="index" class="material-list">
					<!--图片-->
					<template v-if="currentType==0">
						<view class="logo-box">
							<image src="~@/static/img/logo.jpg" class="logo-image"></image>
						</view>
						<view class="right-content">
							<view class="content-name">{{item.materialName}}</view>
							<u-parse v-if="item.materialArticle" :content="item.materialArticle" class="article-text" />
							<image v-if="item.materialImageUrl" :src="baseUrl+item.materialImageUrl" class="material-image material-top-image"
								:style="{width:$util.calculateWidthAndHeight(510),height:$util.calculateWidthAndHeight(770)}"></image>
							<view class="button-area" :class="[item.materialImageUrl?'have-top':'']">
								<button class="button-item" @tap="handleSetting(item,'image')">保存到本地</button>
								<!-- #ifdef APP-PLUS -->
								<button v-if="item.materialImageUrl" class="button-item"
									@tap="shareShowFun(item)">转发到微信</button>
								<!-- #endif -->
							</view>
						</view>
					</template>
					<!--视频-->
					<template v-if="currentType==1">
						<view class="logo-box">
							<image src="~@/static/img/logo.jpg" class="logo-image"></image>
						</view>
						<view class="right-content">
							<view class="content-name">{{item.materialName}}</view>
							<u-parse v-if="item.materialArticle" :content="item.materialArticle" class="article-text" />
							<!-- #ifdef MP-WEIXIN -->
							<video v-if="item.materialVideoUrl" show-center-play-btn
								:src="baseUrl+item.materialVideoUrl" class="material-video" :id="item.id" @play="handlePlay"></video>
							<!-- #endif -->
							
							<!-- #ifdef H5 -->
							<video v-if="item.materialVideoUrl" show-center-play-btn :poster="item.materialVideoUrl+'?x-oss-process=video/snapshot,t_0,f_jpg'"
								:src="baseUrl+item.materialVideoUrl" class="material-video"></video>
							<!-- #endif -->
							
							<!-- #ifdef APP-PLUS -->
							<view v-if="item.materialVideoUrl" class="video-black" @tap="videoshow(item)">
								<image src="~@/static/img/videoPlay.png" mode="aspectFill" class="video-icon"></image>
								<image :src="item.materialVideoUrl+'?x-oss-process=video/snapshot,t_0,f_jpg'" mode="aspectFill"></image>
							</view>
							<!-- #endif -->
							
							<view class="button-area" :class="[item.materialVideoUrl?'have-top':'']">
								<button class="button-item" @tap="handleSetting(item,'video')">保存到本地</button>
								<!-- #ifdef APP-PLUS -->
								<button v-if="item.materialVideoUrl" class="button-item"
									@tap="shareShowFun(item)">转发到微信</button>
								<!-- #endif -->
							</view>
						</view>
					</template>
					<!--文章-->
					<template v-if="currentType==2">
						<view class="article-logo" @tap="jumpToDetail(item)">
							<image v-if="item.materialImageUrl" :src="item.materialImageUrl" mode="aspectFit" class="logo-image"></image>
							<image v-else src="~@/static/img/logo.jpg" class="logo-image"></image>
						</view>
						<view class="right-content" @tap="jumpToDetail(item)">
							<view class="article-text">{{item.materialName}}</view>
							<view class="article-date">{{item.updateTime}}</view>
						</view>
					</template>
				</view>
			</view>
		</mescroll-uni>
		<uni-popup ref="share" :show="shareShow" :type="'bottom'" :custom="true" @change="unishareFun">
			<view class="uni-share">
				<view class="uni-share-title">分享到</view>
				<view class="uni-share-content">
					<view class="uni-share-content-box" @tap="shareFun('WXSceneSession')">
						<view class="uni-share-content-image">
							<view class="iconfont iconweixin shareImg"></view>
						</view>
						<view class="uni-share-content-text">微信好友</view>
					</view>
					<view class="uni-share-content-box" @tap="shareFun('WXSenceTimeline')">
						<view class="uni-share-content-image">
							<view class="iconfont shareImg iconpengyouquan"></view>
						</view>
						<view class="uni-share-content-text">朋友圈</view>
					</view>
				</view>
				<view class="uni-share-btn" @click="cancel()">取消分享</view>
			</view>
		</uni-popup>
		<tui-modal></tui-modal>
		<tui-modal :button="button" :show="modalShow" @click="modalClick" @cancel="modalCancel" title="提示"
			:content="modalContent"></tui-modal>
		<!--app端视频播放-->
		<template v-if="videoPlay">
			<view class="mask-video" @tap="videoPlay = !videoPlay"></view>
			<video class="screen-video" :show-fullscreen-btn="false" :autoplay="true" controls id="myvideo" 
			:src="videoUrl"></video>
		</template>
	</view>
</template>

<script>
	import uParse from '@/components/gaoyia-parse/parse.vue'
	import uniPopup from "@/components/uni-popup/uni-popup.vue"
	import MescrollMixin from '@/components/mescroll-uni/mescroll-mixins.js';
	export default {
		mixins: [MescrollMixin],
		components: {
			uniPopup,
			uParse
		},
		data() {
			return {
				videoPlay: false,
				videoUrl: '', //全屏播放视频的URL
				scrollLeft: 0,
				baseUrl: this.$store.state.imgUrl,
				tabList: [],
				tabs: [{
					name: '线上',
					value: 0,
				}, {
					name: '线下',
					value: 1
				}],
				currentTab: -1,
				wxTypeList:[{
					label: '图片',
					value: 0
				}, {
					label: '文章',
					value: 2
				}],
				nonWxTypeList:[{
					label: '图片',
					value: 0
				}, {
					label: '文章',
					value: 2
				},{
					label: '视频',
					value: 1
				}],
				materialTypeList: [],
				currentType: 0,
				upOption: {
					auto: false, // 不自动加载
					page: {
						num: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
						size: 6 // 每页数据的数量
					},
					noMoreSize: 4, //如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看; 默认5
				},
				materialName: '',
				shareContentType: '',
				shareContent: '',
				materialList: [],
				shareShow: false,
				settingWritePhotosAlbum: false,
				modalContent: '',
				modalShow: false,
				button: [{
					text: "确定",
					type: "primary",
					plain: false
				}],
				shareText: '',
				vid:''
			}
		},
		onReady() {
			// this这个是实例对象  必传
			this.videoContext = uni.createVideoContext("myvideo", this);
		},
		onLoad(options) {
			if (!this.$util.checkTokenAndInviterId(options)) {
				// 检查token和邀请人信息，无token退出方法
				return;
			}
			// #ifdef H5
			this.$wechat.noShare();
			// #endif
			const userType = uni.getStorageSync('orgLv');
			console.log(userType)
			this.tabList = this.tabs;
			this.currentTab = 0;
		},
		methods: {
			handlePlay(event) {
				console.log(event)
				let vid = event.currentTarget.id;
				//关闭上一个播放的视频
				this.vid !== vid && this.videoContext && this.videoContext.stop();
				this.vid = vid;
				//创建控制视频标签的实例对象
				this.videoContext = wx.createVideoContext(vid);
			},
			videoshow(e) {
				//e 是通过点击事件拿到的视屏地址
				this.videoUrl = this.baseUrl + e.materialVideoUrl;
				this.videoContext.requestFullScreen({
					direction: 0 //控制全屏的时候视屏旋转多少度 
				});
				this.videoContext.play();
				this.videoPlay = true; // 显示播放盒子
			},
			//点击其中一个 tab
			swichMenu: async function(current) {
				if (this.currentTab == current) {
					return false;
				} else {
					this.materialList = [];
					this.currentTab = current;
					this.getMaterialAll({
						num: 1,
						size: 6
					});
				}
			},
			cancel() {
				this.shareShow = false
			},
			unishareFun(e) {
				console.log(e.show)
				this.shareShow = e.show
			},
			shareShowFun(item) {
				this.materialName = item.materialName;
				this.shareText = item.materialArticle.replace(/<[^<>]+>/g, "");
				this.shareContentType = item.materialType;
				if (item.materialType == 0) {
					// 图片
					this.shareContent = item.materialImageUrl;
				} else if (item.materialType == 1) {
					// 视频
					this.shareContent = item.materialVideoUrl;
				}
				this.shareShow = true;
			},
			unipopupFun(e) {
				console.log(e.show)
				this.couponShow = e.show;
			},
			//分享
			shareFun(type) {
				let that = this;
				if (this.shareContentType == 0) {
					// 图片
					// #ifdef APP-PLUS
					uni.setClipboardData({
						data: this.shareText,
						success: function() {
						}
					});
					uni.share({
						provider: 'weixin',
						scene: type,
						type: 2,
						title: this.materialName,
						imageUrl: this.baseUrl + this.shareContent,
						success: function(res) {
							console.log('success:' + JSON.stringify(res));
							uni.showToast({
								title:'分享成功'
							})
						},
						fail: function(err) {
							console.log('fail:' + JSON.stringify(err));
							uni.showToast({
								title: '分享失败'
							});
						}
					})
					this.cancel();
					// #endif
				} else if (this.shareContentType == 1) {
					// 视频
					// #ifdef APP-PLUS
					uni.setClipboardData({
						data: this.shareText,
						success: function() {
						}
					});
					uni.share({
						provider: 'weixin',
						scene: type,
						type: 4,
						title: this.materialName,
						mediaUrl: this.baseUrl + this.shareContent,
						success: function(res) {
							uni.showToast({
								title: '分享成功'
							});
						},
						fail: function(err) {
							uni.showToast({
								title: '分享失败'
							});
						}
					})
					this.cancel();
					// #endif
				}
			},
			// 修改素材类型
			tapMaterialType(item) {
				if (this.currentType == item.value) {
					return false;
				} else {
					this.materialList = [];
					this.currentType = item.value;
					this.getMaterialAll({
						num: 1,
						size: 6
					});
				}
			},
			initMaterialAll() {
				this.mescroll.resetUpScroll();
			},
			getMaterialAll(page) {
				let params = {
					current: page.num,
					pageSize: page.size,
				};
				params.materialUseType = this.currentTab; //0:DR商城，1:ES管家
				params.materialType = this.currentType; //0:图片，1:视频，2:文章
				console.log(params);
				this.$http.getMaterialList(params).then((res) => {
					if (res.status === 0) {
						// status 0:已发布 1:未发布
						let curPageData = res.data.records.filter(i => i.status == 0);
						this.mescroll.endSuccess(res.data.records.length);
						if (page.num == 1) {
							this.materialList = []
						};
						this.materialList = this.materialList.concat(curPageData);
						this.materialList.forEach(i => {
							if (i.materialArticle) {
								i.materialArticle = i.materialArticle.replace(/&nbsp;/g, ' ');
							}
						})
					}
				}).catch(() => {
					this.mescroll.endErr()
				});
			},
			modalClick(e) {
				let index = e.index;
				if (index == 0) {
					// 取消
					this.modalCancel();
				}
			},
			modalCancel() {
				this.modalShow = false;
			},
			// 保存到本地
			handleSetting(item, type) {
				// #ifdef H5
				this.modalShow = true;
				this.modalContent = type == 'image' ? '请长按图片保存到本地' : '如需保存视频请前往app或小程序';
				// #endif
				// #ifndef H5
				if (type == 'image') {
					if (!item.materialImageUrl) {
						this.$util.toast('无图片素材，无法保存');
						return;
					}
					this.handleSave(item, type);
				} else {
					if (!item.materialVideoUrl) {
						this.$util.toast('无视频素材，无法保存');
						return;
					}
					this.handleSave(item, type);
				}
				// #endif
			},
			// 保存文件
			handleSave(item, type) {
				const that = this;
				// #ifdef MP-WEIXIN
				uni.showLoading({
					title: type == 'image' ? '图片保存中' : '视频保存中'
				});
				if (this.settingWritePhotosAlbum) {
					uni.getSetting({
						success: res => {
							if (res.authSetting['scope.writePhotosAlbum']) {
								that.downloadToLocal(item, type);
							} else {
								uni.authorize({
									scope: 'scope.writePhotosAlbum',
									success: () => {
										that.downloadToLocal(item, type);
									},
									fail: () => {
										console.log(77)
										uni.hideLoading();
										// that.$util.toast('保存失败,请先在设置页面打开“保存相册”使用权限');
										uni.openSetting();
										this.settingWritePhotosAlbum = false;
									}
								});
							}
						}
					});
				} else {
					this.settingWritePhotosAlbum = true;
					uni.authorize({
						scope: 'scope.writePhotosAlbum',
						success: () => {
							that.downloadToLocal(item, type);
						},
						fail: () => {
							uni.hideLoading();
							// that.$util.toast('保存失败,请先在设置页面打开“保存相册”使用权限');
							uni.openSetting();
						}
					});
				}
				// #endif
				// #ifdef APP-PLUS
				uni.showLoading({
					title: type == 'image' ? '图片保存中' : '视频保存中'
				});
				that.downloadToLocal(item, type);
				// #endif
			},
			// 下载到本地
			downloadToLocal(item, type) {
				const that = this;
				let downloadUrl = type == 'image' ? that.baseUrl + item.materialImageUrl : that.baseUrl + item.materialVideoUrl;
				console.log(downloadUrl)
				uni.downloadFile({
					url: downloadUrl, // 下载地址  
					success: (data) => {
						if (data.statusCode === 200) {
							if (type == 'image') {
								// #ifdef APP-PLUS
								let imageUrl;
								if (uni.getSystemInfoSync().platform == "ios") {
									// ios下载后临时地址无后缀改用原本地址
									imageUrl = downloadUrl;
								} else {
									imageUrl = data.tempFilePath;
								}
								uni.saveImageToPhotosAlbum({ // 需要保存到相册
									filePath: imageUrl, // 本地临时地址  
									success: (res) => {
										that.$util.toast('保存成功', 'success');
									},
									fail: () => {
										that.$util.toast('保存失败');
									}
								});
								// #endif
								// #ifndef APP-PLUS
								uni.saveImageToPhotosAlbum({ // 需要保存到相册
									filePath: data.tempFilePath, // 本地临时地址  
									success: (res) => {
										that.$util.toast('保存成功', 'success');
									},
									fail: () => {
										that.$util.toast('保存失败');
									}
								});
								// #endif
							} else {
								uni.saveVideoToPhotosAlbum({ // 需要保存到相册
									filePath: data.tempFilePath, // 本地临时地址  
									success: (res) => {
										that.$util.toast('保存成功', 'success');
									},
									fail: () => {
										that.$util.toast('保存失败');
									}
								});
							}

						}
					}
				});
			},
			// 去往详情页
			jumpToDetail(item) {
				// #ifdef H5
				if (this.$wechat.isIOS()) {
					window.location.href = `/h5/packageC/pages/material/materialDetail?id=${item.id}&share=1`
				} else {
					uni.navigateTo({
						url: `/packageC/pages/material/materialDetail?id=${item.id}`
					})
				}
				// #endif
				// #ifndef H5
				uni.navigateTo({
					url: `/packageC/pages/material/materialDetail?id=${item.id}`
				})
				// #endif
			}
		}
	}
</script>

<style lang="scss">
	.material-wrapper {
		.mask-video {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background: rgba(0, 0, 0, 0.6);
			z-index: 9999;
		}
		.screen-video {
			position: fixed;
			left: 50%;
			top: 50%;
			margin-top: -50%;
			margin-left: -50%;
			width: 100%;
			// height: 100vh;
		}

		.fixed-area {
			position: fixed;
			left: 0;
			z-index: 888;
			right: 0;
			top: 0;

			.top-tabs-view {
				width: 100%;
				box-sizing: border-box;
				display: flex;
				align-items: center;
				justify-content: space-between;
				box-shadow: 0 0 4rpx #eee;
				white-space: nowrap;
				height: 80rpx;
				background-color: #fff;

				.tabs-item-wrap {
					display: inline-block;
					white-space: nowrap;
					width: 50%;

					.tabs-item {
						margin-left: 35rpx;
						margin-right: 30rpx;
						position: relative;
						height: 100%;
						display: flex;
						align-items: center;
						justify-content: center;

						.tabs-item-txt {
							height: 74rpx;
							line-height: 80rpx;
							font-size: 28rpx;
							color: #999999;

							&.theme-color {
								color: #111111;
							}
						}

						.tabs-item-bottom {
							position: absolute;
							bottom: 0rpx;
							width: 80rpx;
							height: 6rpx;
							border-radius: 4rpx;
							left: calc(50% - 40rpx);
							&.theme-color {
								background: #EE0A24;
							}
						}
					}
				}
			}

			.material-type {
				display: flex;
				justify-content: space-between;
				padding: 18rpx 64rpx;
				background-color: #FFFFFF;

				.type-item {
					width: 100rpx;
					height: 44rpx;
					background: #F5F5F5;
					border-radius: 22rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					color: #111111;
					font-size: 24rpx;
				}

				.select-type {
					background: linear-gradient(151deg, #F69E97 0%, #EA655E 100%);
					color: #fff;
				}
			}
		}

		.material-con {
			.material-list {
				padding: 32rpx;
				background-color: #fff;
				display: flex;
				margin-bottom: 16rpx;

				.logo-box {
					// background: #FC5A57;
					border-radius: 50%;
					height: 80rpx;
					width: 80rpx;
					display: flex;
					justify-content: center;
					align-items: center;

					.logo-image {
						// width: 50rpx;
						// height: 50rpx;
						width:100%;
						height:100%;
					}
				}

				.article-logo {
					width: 120rpx;
					height: 120rpx;
					border-radius: 10rpx;
					// background: #FC5A57;
					display: flex;
					justify-content: center;
					align-items: center;

					.logo-image {
						width: 100%;
						height: 100%;
					}
				}



				.right-content {
					flex: 1;
					margin-left: 16rpx;

					.article-text {
						margin-top: 4rpx;
						font-size: 28rpx;
						margin-bottom: 22rpx;
						min-height: 60rpx;
					}

					.material-article {
						font-size: 28rpx;
					}

					.article-date {
						color: #999999;
						font-size: 24rpx;
					}

					.content-name {
						color: #111111;
						font-size: 30rpx;
						margin-bottom: 8rpx;
						font-weight: bold;
					}
					
					.article {
						font-size: 28rpx;
						margin-bottom: 8rpx;
						text-align: justify;
					}

					.material-image {
						width: 400rpx;
						height: 400rpx;
					}
					
					.material-top-image {
						margin-top: 16rpx;
					}

					.material-video {
						width: 400rpx;
						height: 224rpx;
					}

					.video-black {
						width: 400rpx;
						height: 224rpx;
						// background: #000000;
						position: relative;

						.video-icon {
							width: 60rpx;
							height: 60rpx;
							position: absolute;
							top: 50%;
							left: 50%;
							margin-left: -30rpx;
							margin-top: -30rpx;
							z-index:9999;
						}
						image {
							width: 100%;
							height: 100%;
						}
					}

					.button-area {
						display: flex;

						&.have-top {
							margin-top: 32rpx;
						}

						.button-item {
							background: linear-gradient(151deg, #F69E97 0%, #EA655E 100%);
							border-radius: 50rpx;
							display: flex;
							justify-content: center;
							align-items: center;
							color: #fff;
							font-size: 28rpx;
							width: 240rpx;

							&:first-child {
								margin-right: 24rpx;
							}
						}
					}
				}
			}
		}

		/* 底部分享 */
		.uni-share {
			background: #fff;


			.uni-share-title {
				line-height: 60upx;
				font-size: 24upx;
				padding: 15upx 0;
				text-align: center;
			}

			.uni-share-content {
				display: flex;
				flex-wrap: wrap;
				padding: 15px;
			}

			.uni-share-content-box {
				display: flex;
				flex-direction: column;
				align-items: center;
				width: 25%;
				box-sizing: border-box;
			}

			.uni-share-content-image {
				display: flex;
				justify-content: center;
				align-items: center;
				// width: 60upx;
				// height: 60upx;
				overflow: hidden;
				border-radius: 10upx;
			}

			.shareImg {
				color: #07C160;
				font-size: 60rpx;
			}

			.uni-share-content-image .image {
				width: 100%;
				height: 100%;
			}

			.uni-share-content-text {
				font-size: 26upx;
				color: #333;
				padding-top: 5px;
				padding-bottom: 10px;
			}

			.uni-share-btn {
				height: 90upx;
				line-height: 90upx;
				border-top: 1px #f5f5f5 solid;
				text-align: center;
				color: #666;
			}
		}
	}
</style>
